<template>
	<view :class="uiStyle == 1 ? '' : 'uiStyle'">
		<!-- 申请车位-第一步关联小区选中 -->
		<view>
			<!-- 拍照 -->
			<view class="step-first">
				<view class="input-title">请上传本人机动车行驶证</view>
				<view class="upload-area" style="text-align: center">
					<view class="upload-box" v-if="fileList.length == 0" @click="uplodaImg">
						<image mode="widthFix" src="../../static/assets/img/example.png"></image>
					</view>
					<view class="upload-box" v-else @click="uplodaImg">
						<image mode="widthFix" :src="fileList[0].url"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="step-bottom">
			<view class="line"></view>
			<view class="info" style="color: #666666">拍摄要求</view>
			<view class="line"></view>
		</view>
		<view class="step-bottom step-bottom2" style="width: 100%">
			<image class="example2" src="../../static/assets/img/example2.png" mode="widthFix"></image>
		</view>
	</view>
</template>

<script>
	// pages/applyStep1/applyStep1.js
	import util from './../../utils/util.js';
	import api from './../../utils/api.js';
	import { pathToBase64, base64ToPath } from 'image-tools'
	export default {
		data() {
			return {
				picUrlList: [],

				//证明材料
				fileList: [],

				/**
				 * 页面的初始数据
				 */
				licenseUrl: '',

				plateNo: '',
				faceImageUrl: '',
				uiStyle: 1
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad: function(options) {
			this.uiStyle = uni.getStorageSync('uiStyle')
			this.setData({
				plateNo: options.id
			});
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		// onShareAppMessage: function () {
		// }
		onReachBottom: function() {},
		/**
		 * 用户点击右上角分享
		 */
		methods: {
			// 下一步
			nextStep() {},
			getImageInfo(src) {
				let _this = this
				uni.getImageInfo({
					src,
					success(res) {
						console.log(res)
						let canvasWidth = res.width //图片原始长宽
						let canvasHeight = res.height
						let ratio = canvasWidth / canvasHeight;
						if (canvasWidth > 200) {
							canvasWidth = 200;
							canvasHeight = Math.floor(canvasWidth / ratio);
						}

						let img = new Image()
						img.src = res.path
						let canvas = document.createElement('canvas');
						let ctx = canvas.getContext('2d')
						canvas.width = canvasWidth
						canvas.height = canvasHeight
						ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
						canvas.toBlob(function(fileSrc) {
							console.log(fileSrc)
							window.URL = window.URL || window.webkitURL
							let imgSrc = window.URL.createObjectURL(fileSrc)
							pathToBase64(imgSrc)
							  .then(item => {
								_this.uploadfile(item)
							  })
							  .catch(error => {
							    console.error(error)
							  })
						})
					}
				})
			},
			uploadfile(imgSrc){
				var that = this
				uni.showLoading()
				uni.uploadFile({
					url: api.vueUpload,
					filePath: imgSrc,
					name: 'file',
					formData: {
						user: 'test'
					},
					header: {
						Authorization: uni.getStorageSync('AUTHORIZATION') //如果需要token的话要传
					},
					success: item => {
						if (item.statusCode == 200) {
							var data = JSON.parse(item.data);
							let pic = that.picUrlList;
				
							if (!data.data) {
								uni.showToast({
										title: data.msg,
										icon: 'none'
									},
									2000
								);
								return;
							}
				
							pic.push(data.data);
							that.setData({
								picUrlList: pic,
								licenseUrl: data.data
							});
							if (data.data) {
								util.request(api.getEncryPath + '?path=' + data.data, '',
									'POST').then((res) => {
									let arr = that.fileList;
									arr.push({
										url: res
									});
									that.setData({
										fileList: arr
									});
									var licensePar = {
										unionId: uni.getStorageSync('unionId'),
										plateNo: that.plateNo,
										picUrl: that.licenseUrl,
										type: 'photo'
									};
									util.request(api.ocrCheck, licensePar, 'POST')
										.then((res) => {
											if (res.success) {
												if (res.data == 1) {
													uni.showToast({
															title: '认证成功,将返回上一步',
															icon: 'none'
														},
														2000
													);
													setTimeout(function() {
														uni.navigateBack({
															delta: 1
														});
													}, 2000);
												} else {
													uni.showToast({
															title: '车牌号码不匹配，请重新提交！',
															icon: 'none'
														},
														2000
													);
												}
											} else {
												uni.showToast({
													title: res.msg ||
														'接口出错了，请稍后再试',
													icon: 'none'
												});
											}
										});
								});
							}
						} else {
							uni.showToast({
								title: '上传失败，请重新上传',
								icon: 'error'
							})
						}
					},
					fail: (err) => {
						console.log('uploadImage fail', err);
						uni.showToast({
							title: '上传失败，请重新上传',
							icon: 'error'
						})
					}
				})
			},
			uplodaImg() {
				let that = this;
				uni.chooseImage({
					count: 1, // 默认最多一次选择9张图
					success: res => {
						if(res.tempFiles[0].size > 524288){
							this.getImageInfo(res.tempFilePaths[0])
						}else{
							this.uploadfile(res.tempFilePaths[0])
						}
					}
				})
			},
			// 上传车牌
			afterRead(event) {
				const {
					file
				} = event.detail; // this.setData({ fileList: event.detail.file.url });
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

				var that = this; //坑1： this需要这么处理

				uni.uploadFile({
					url: api.vueUploadcarOcr,
					// 仅为示例，非真实的接口地址
					filePath: file.url,
					name: 'file',
					formData: {
						user: 'test'
					},
					header: {
						Authorization: uni.getStorageSync('AUTHORIZATION') //如果需要token的话要传
					},

					success(res) {
						var data = JSON.parse(res.data);
						let pic = that.picUrlList;

						if (!data.data) {
							uni.showToast({
									title: data.msg,
									icon: 'none'
								},
								2000
							);
							return;
						}

						pic.push(data.data);
						console.log('success');
						that.setData({
							picUrlList: pic,
							licenseUrl: data.data
						});

						if (data.data) {
							util.request(api.getEncryPath + '?path=' + data.data, '', 'POST').then((res) => {
								let arr = that.fileList;
								arr.push({
									url: res
								});
								that.setData({
									fileList: arr
								});
								var licensePar = {
									unionId: uni.getStorageSync('unionId'),
									plateNo: that.plateNo,
									picUrl: that.licenseUrl,
									type: 'photo'
								};
								util.request(api.ocrCheck, licensePar, 'POST').then((res) => {
									if (res.success) {
										if (res.data == 1) {
											uni.showToast({
													title: '认证成功,将返回上一步',
													icon: 'none'
												},
												2000
											);
											setTimeout(function() {
												uni.navigateBack({
													delta: 1
												});
											}, 2000);
										} else {
											uni.showToast({
													title: '车牌号码不匹配，请重新提交！',
													icon: 'none'
												},
												2000
											);
										}
									} else {
										uni.showToast({
											title: res.msg || '接口出错了，请稍后再试',
											icon: 'none'
										});
									}
								});
							});
						}
					},

					fail(res) {
						console.log(res);
						uni.showToast({
								title: '抱歉！图片不符合要求，或可能图片太大导致！',
								icon: 'none'
							},
							2000
						);
					}
				});
			},

			deleteFun(e) {
				let del = e.detail.index;
				let file = this.fileList;
				let pic = this.picUrlList;
				file.splice(del, 1);
				pic.splice(del, 1);
				this.setData({
					fileList: file,
					picUrlList: pic,
					licenseUrl: ''
				});
			}
		}
	};
</script>
<style>
	@import './licenseIdentify.css';
</style>
